<template>
  <div class="mall-picture">
    <div class="top">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="商城图片魔方" name="first" />
      </el-tabs>
    </div>
    <div class="middle">
      <div class="title">
        <h3>首页模块</h3>
        <el-button type="primary" @click="addModuleItem">添加图片模块</el-button>
      </div>
      <div class="middle-box">
        <div class="noSortBox">
          <el-table :data="noSortableList" border row-key="id">
            <el-table-column align="center">
              <template slot-scope="scope">
                <div>
                  <span>{{ scope.row.module_name }}</span>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div v-if="sortableList.length" class="sortBox">
          <el-table :data="sortableList" border row-key="id">
            <el-table-column align="center">
              <template slot-scope="scope">
                <div class="cell-wrapper" :class="isSort(scope)">
                  <i v-if="scope.row.is_edit" class="icon-drag" />
                  <!-- <span>{{ scope.row.module_name }}</span> -->
                  <el-input v-model="scope.row.module_name" :class="{ 'resitCls' : !scope.row.is_edit }" :disabled="!scope.row.is_edit" size="mini" style="width: 120px" @blur="handleInputBlur(scope)" />
                  <div v-if="scope.row.is_edit" class="button-wrapper">
                    <el-button type="primary" @click="moduleEdit(scope)">编辑</el-button>
                    <el-button type="primary" @click="deleteModuleItem(scope)">删除</el-button>
                  </div>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <AddMallEdit :id="id" ref="addMallEdit" @alreadySubmit="handleAlreadySubmit" />
  </div>
</template>
<script>
import AddMallEdit from './component/add-mall-edit'
import { getMallModuleList, setSortMoudleItem, addMoudleItem, deleteModule, setModuleName } from '@/api/add-mall'
const ERR_OK = 200
export default {
  components: {
    AddMallEdit
  },
  data() {
    return {
      activeName: 'first',
      noSortableList: [],
      sortableList: [],
      len: 0,
      index: 3,
      module_id: '',
      id: ''
    }
  },
  mounted() {
    this._getMallModuleList()
      .then(() => {
        this.rowDrop()
      })
      .catch(err => {
        console.log(err)
      })
  },
  methods: {
    isSort(scope) {
      const readySort = !!scope.row.is_edit
      return { isSort: readySort }
    },
    handleInputBlur(scope) {
      this._setModuleName({ module_id: scope.row.id, module_name: scope.row.module_name })
    },
    handleAlreadySubmit() {
      this._getMallModuleList()
    },
    moduleEdit(scope) {
      this.$refs.addMallEdit.show()
      this.id = scope.row.id
    },
    deleteModuleItem(scope) {
      this._deleteModule(scope.row.id)
        .then(() => {
          const fIndex = this.sortableList.findIndex((item, index) => {
            return item.id === scope.row.id
          })
          if (fIndex >= 0) {
            this.sortableList.splice(fIndex, 1)
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    handleClick(tab, event) {
      console.log(tab, event)
    },
    addModuleItem() {
      // this.list.push({ module_name: '图片模块', sort: _index, id: _index })
      this._addMoudleItem()
        .then(res => {
          this.sortableList.push({ module_name: '图片模块', module_id: this.module_id, id: this.module_id, is_edit: 1 })
        })
    },
    rowDrop() {
      const tbody = document.querySelector('.sortBox .el-table .el-table__body-wrapper tbody')
      const _this = this
      Sortable.create(tbody, {
        handle: '.isSort',
        onEnd({ newIndex, oldIndex }) {
          // const currRow = _this.tableData.splice(oldIndex, 1)[0]
          // _this.tableData.splice(newIndex, 0, currRow)
          // 改变数组的顺序
          _this.sortFromDrag(newIndex, oldIndex)
          const pArr = _this.sortableList.map((item, index) => {
            return item.id
          })
          const allMuduleId = _this.notSortModuleId().concat(pArr)
          _this._setSortMoudleItem({ module_id: allMuduleId })
        }
      })
    },
    notSortModuleId() {
      return this.noSortableList.map((item, index) => {
        return item.id
      })
    },
    sortFromDrag(newIndex, oldIndex) {
      if (newIndex === oldIndex) return
      if (newIndex < oldIndex) {
        const temp1 = this.sortableList[oldIndex]
        for (let i = oldIndex; i > newIndex; i--) {
          this.sortableList[i] = this.sortableList[i - 1]
        }
        this.sortableList[newIndex] = temp1
      }
      if (newIndex > oldIndex) {
        const temp1 = this.sortableList[oldIndex]
        for (let i = oldIndex; i < newIndex; i++) {
          this.sortableList[i] = this.sortableList[i + 1]
        }
        this.sortableList[newIndex] = temp1
      }
    },
    _getMallModuleList() {
      return getMallModuleList()
        .then(res => {
          if (res.code === ERR_OK) {
            console.log(res)
            if (res.data.list.length > 3) {
              this.noSortableList = res.data.list.slice(0, 3)
              this.sortableList = res.data.list.slice(3)
            } else {
              this.noSortableList = res.data.list
            }
            return Promise.resolve()
          }
        })
        .catch(err => {
          console.log(err)
          return Promise.reject(err)
        })
    },
    _addMoudleItem() {
      return new Promise((resolve, reject) => {
        addMoudleItem()
          .then(res => {
            if (res.code === ERR_OK) {
              console.log(res)
              resolve(res)
              this.module_id = res.data.module_id
            }
          })
          .catch(err => {
            console.log(err)
            reject(err)
          })
      })
    },
    _setSortMoudleItem({ module_id }) {
      setSortMoudleItem({ module_id })
        .then(res => {
          if (res.code === ERR_OK) {
            console.log(res)
            this._success('排序成功')
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    _deleteModule(module_id) {
      return new Promise((resolve, reject) => {
        deleteModule(module_id)
          .then(res => {
            if (res.code === ERR_OK) {
              console.log(res)
              this._success('删除成功')
              resolve()
            }
          })
          .catch(err => {
            console.log(err)
            reject(err)
          })
      })
    },
    _setModuleName({ module_id, module_name }) {
      setModuleName({ module_id, module_name })
        .then(res => {
          if (res.code === ERR_OK) {
            this._success('修改成功')
          }
        })
    },
    _success(message) {
      this.$message({
        type: 'success',
        message: message,
        showClose: true
      })
    }
  }
}
</script>
<style lang="scss" scoped>
@import '@/styles/el-button.scss';
.resitCls /deep/ input{
  background: none !important;
  border: none !important;
  color: #444 !important;
}
.mall-picture {
  padding: 0 20px;
  box-sizing: border-box;
  .top {
    margin-top: 10px;
  }
  .middle {
    .title {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 468px;
      h3 {
        color: rgba(51, 51, 51, 1);
        font-size: 18px;
        font-family: Roboto;
        margin-bottom: 10px;
      }
    }
  }
}
.el-tabs /deep/ .el-tabs__item {
  line-height: 26px;
  color: rgba(51, 51, 51, 1);
  font-size: 18px;
  text-align: center;
  font-family: Roboto;
  font-weight: bold;
}
.el-tabs /deep/.el-tabs__active-bar {
  height: 3px !important;
}
.el-table {
  width: 468px;
  background-color: rgba(250, 250, 250, 1);
  text-align: center;
}
.el-table /deep/ .has-gutter tr th {
  line-height: 20px;
  background-color: rgba(250, 250, 250, 1);
  text-align: center;
}
.el-table /deep/ .el-table__row {
    line-height: 20px;
    background-color: rgba(250, 250, 250, 1);
    text-align: center;
}
.el-table /deep/ .has-gutter{
  display: none;
}
.cell-wrapper {
  position: relative;
  .icon-drag {
    position: absolute;
    left: 10px;
    top: 50%;
    transform: translateY(-50%);
    display: inline-block;
    width: 20px;
    height: 20px;
    background: url("./../../assets/drap.png") no-repeat;
    background-size: cover;
  }
  .button-wrapper{
    position: absolute;
    right: 10px;
    top: 50%;
    transform: translateY(-50%);
    display: flex;
    align-items: center;
   .el-button{
      width: 60px;
      padding: 10px 10px !important;
      border-radius: 8px;
      overflow: hidden;
      padding: 0 !important;
      span{
        vertical-align: top;
      }
    }
  }
}
.el-input /deep/ input{
  text-align: center;
  font-size: 14px;
  background: #fafafa;
  // border: none;
}
</style>
